package com.leyou.getway.Filter;

import com.auth.constants.JwtConstants;
import com.auth.dto.Payload;
import com.auth.dto.UserDetails;
import com.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
//为啥实现这俩
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取cookie
        HttpCookie cookie = request.getCookies().getFirst(JwtConstants.COOKIE_NAME);
        //无登录，放行
        if (cookie==null){
            return chain.filter(exchange);
        }
        try {
            //获取token并校验
            String jwt = cookie.getValue();
            // 3.1.解析并验证token
            Payload payload = jwtUtils.parseJwt(jwt);
            // 3.2.获取用户
            UserDetails userInfo = payload.getUserDetail();
            // 3.3.刷新jwt
            jwtUtils.refreshJwt(userInfo.getId());
            log.info("用户{}正在访问{}", userInfo.getUsername(), request.getURI().getPath());
        } catch (Exception e) {
            log.info("用户未登录");
        }

        // 5.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 登录拦截，可以采用最高优先级,老师说用最低等级就可以
        return HIGHEST_PRECEDENCE;
    }
}
